#include <iostream>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>

using std::cout;
using std::endl;

// 全局的锁和条件变量
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

bool gloop = true;

enum NUM
{
    SIZE = 1024,
    NUMS = 5
};
void *mywait(void *args)
{
    std::string s = static_cast<char *>(args);
    while (true && gloop)
    {
        pthread_mutex_lock(&gmutex);
        pthread_cond_wait(&gcond, &gmutex);
        usleep(100000);

        cout << s.c_str() << endl;

        pthread_mutex_unlock(&gmutex);
    }
    return nullptr;
}
void Stop(int sig)
{
    gloop = false;
    cout << sig << "delivered" << endl;
    cout << "stop looping" << endl;
}
int main()
{
    cout << "father start pid:" << getpid() << endl;
    std::vector<pthread_t> threads(NUMS);
    for (int i = 0; i < NUMS; ++i)
    {
        char *name = new char[SIZE];
        snprintf(name, SIZE, "thread-%d", i + 1);

        pthread_create(&threads[i], nullptr, mywait, (void *)name);
    }
    // 线程控制
    while (gloop)
    {
        signal(3, Stop);
        pthread_cond_signal(&gcond);
        cout << "wake up a thread" << endl;
        sleep(1);
    }
    // pthread_cond_broadcast(&gcond);

    for (int i = 0; i < NUMS; ++i)
    {
        pthread_join(threads[i], nullptr);
    }
    cout << "join success ,father done" << endl;

    return 0;
}